package com.netease.nim.demo.session.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ciko.code.bean.UserBean;
import com.netease.nim.demo.NimCache;
import com.netease.nim.demo.common.media.picker.activity.PreviewImageFromCameraActivity;
import com.netease.nim.demo.common.ui.dialog.CustomAlertDialog;
import com.netease.nim.demo.common.ui.dialog.CustomAlertDialog.onSeparateItemClickListener;
import com.netease.nim.demo.common.ui.dialog.EasyAlertDialog;
import com.netease.nim.demo.common.ui.dialog.EasyAlertDialogHelper;
import com.netease.nim.demo.common.ui.dialog.EasyAlertDialogHelper.OnDialogActionListener;
import com.netease.nim.demo.common.ui.imageview.HeadImageView;
import com.netease.nim.demo.common.ui.listview.ListViewUtil;
import com.netease.nim.demo.common.util.media.ImageUtil;
import com.netease.nim.demo.common.util.string.StringUtil;
import com.netease.nim.demo.common.util.sys.ClipboardUtil;
import com.netease.nim.demo.file.browser.FileBrowserActivity;
import com.netease.nim.demo.main.activity.NimAVChatActivity;
import com.netease.nim.demo.main.model.Extras;
import com.netease.nim.demo.session.adapter.MoreFunctionGridviewAdapter.MoreFunctionItemHolder;
import com.netease.nim.demo.session.adapter.MoreFunctionGridviewAdapter.onMoreFunctionItemClickListener;
import com.netease.nim.demo.session.adapter.MoreFunctionPagerAdapter;
import com.netease.nim.demo.session.emoji.EmoticonView;
import com.netease.nim.demo.session.emoji.IEmojiSelectedListener;
import com.netease.nim.demo.session.emoji.MoonUtil;
import com.netease.nim.demo.session.helper.MessageHelper;
import com.netease.nim.demo.session.helper.SendImageHelper;
import com.netease.nim.demo.session.helper.VideoMessageHelper;
import com.netease.nim.demo.session.helper.VideoMessageHelper.VideoMessageHelperListener;
import com.netease.nim.demo.session.model.ActivityResultCode;
import com.netease.nim.demo.session.model.MsgListItem;
import com.netease.nim.demo.session.model.extension.GuessAttachment;
import com.netease.nim.demo.team.activity.TeamNicknameActivity;
import com.netease.nim.demo.util.AttachmentStore;
import com.netease.nim.demo.util.storage.StorageType;
import com.netease.nim.demo.util.storage.StorageUtil;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.avchat.constant.AVChatType;
import com.netease.nimlib.sdk.media.record.AudioRecorder;
import com.netease.nimlib.sdk.media.record.IAudioRecordCallback;
import com.netease.nimlib.sdk.media.record.RecordType;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.constant.MsgStatusEnum;
import com.netease.nimlib.sdk.msg.constant.MsgTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.shwread.android.qysw.activity.NewInteractionCreateTeamChMActivity;
import com.shwread.android.qysw10000182.R;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import logic.constants.DefaultConsts;
import logic.dao.UserDao;
import logic.util.Util;


/**
 * 聊天界面抽象类（封装基础UI）
 * <p/>
 * Created by huangjun on 2015/2/1.
 */
public abstract class AbsMessageActivity
        extends
        AbsBaseMessageActivity
        implements
        IAudioRecordCallback,
        IEmojiSelectedListener
{
	
	// constant
	private static final int               SHOW_LAYOUT_DELAY               = 200;
	public static final int                PICK_IMAGE_COUNT                = 9;
	public static final String             JPG                             = ".jpg";
	public static final String             MIME_JPEG                       = "image/jpeg";
	
	// state
	private boolean                        moreFuntionBottomLayoutHasSetup = false;
	
	// view
	protected ViewGroup                    listviewContainer;
	protected View                         moreFuntionBottomLayout;                       // 更多布局
	protected LinearLayout                 messageActivityBottomLayout;
	public EditText                        messageEditText;                               // 文本消息编辑框
	protected Button                       audioRecordBtn;                                // 录音按钮
	protected FrameLayout                  audioAnimLayout;                               // 录音动画布局
	protected View                         switchToTextButtonInInputBar;                  // 文本消息选择按钮
	protected View                         switchToAudioButtonInInputBar;                 // 语音消息选择按钮
	protected View                         moreFuntionButtonInInputBar;                   // 更多消息选择按钮
	protected View                         sendMessageButtonInInputBar;                   // 发送消息按钮
	protected View                         emojiButtonInInputBar;                         // 发送消息按钮
	protected View                         messageInputBar;
	
	// 表情
	private LinearLayout                   emojiLayout;                                   // 表情root
	protected ViewPager                    viewPager;                                     // 表情翻页
	protected LinearLayout                 emojiPage;                                     // 表情indicator
	protected EmoticonView                 gifView                         = null;
	
	// 底部新消息提示条
	private View                           newMessageTipLayout;
	private TextView                       newMessageTipTextView;
	private HeadImageView                  newMessageTipHeadImageView;
	
	// adapter
	protected List<MoreFunctionItemHolder> moreFunctionItemHolders;                       // 更多
	                                                                                       
	// 菜单
	protected MenuItem                     menuItem;
	
	// 语音
	protected AudioRecorder                audioMessageHelper;
	private Chronometer                    time;
	private TextView                       timerTip;
	private LinearLayout                   timerTipContainer;
	private boolean                        started                         = false;
	private boolean                        cancelled                       = false;
	private boolean                        touched                         = false;       // 是否按着
	                                                                                       
	// 图片
	private SendImageAfterResumeData       sendImageAfterResumeData;
	
	// 视频
	protected VideoMessageHelper           videoMessageHelper;
	
	/**
	 * ************************* life cycle **************************
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		findViews();
		initInputBar();
		initTextEdit();
		initAudioRecordButton();
		restoreText(false);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(getMenuRes(), menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		onMenuKeyPressed(item.getItemId());
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		// 停止录音
		if (audioMessageHelper != null)
		{
			onEndAudioRecord(true);
		}
		
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		sendImageAfterResume();
		setVolumeControlStream(AudioManager.STREAM_VOICE_CALL); // 默认使用听筒播放
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
	
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		removeHandlerCallback();
		hideInputMethod();
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != RESULT_OK) { return; }
		if (requestCode == ActivityResultCode.PICK_IMAGE)
		{
			onPickImageActivityResult(data, requestCode);
		}
		else if (requestCode == ActivityResultCode.PREVIEW_IMAGE_FROM_CAMERA)
		{
			onPreviewImageActivityResult(requestCode, resultCode, data);
		}
		else if (requestCode == ActivityResultCode.GET_LOCAL_VIDEO)
		{
			videoMessageHelper.onGetLocalVideoResult(requestCode, resultCode, data);
		}
		else if (requestCode == ActivityResultCode.CAPTURE_VIDEO)
		{
			videoMessageHelper.onCaptureVideoResult(requestCode, resultCode, data);
		}
		//TODO fw location
		//        else if (requestCode == ActivityResultCode.LOCATION_ACTIVITY_CODE) {
		//            double latitude = data.getDoubleExtra(ILocationActivity.LATITUDE, 39.915);
		//            double longitude = data.getDoubleExtra(ILocationActivity.LONGITUDE, 116.404);
		//            String address = data.getStringExtra(ILocationActivity.ADDRESSS);
		//            sendLocationMessage(latitude, longitude, address);
		//        } 
		else if (requestCode == ActivityResultCode.GET_LOCAL_FILE)
		{
			String path = data.getStringExtra(FileBrowserActivity.EXTRA_DATA_PATH);
			sendLocalFile(path);
		}
		else if (requestCode == TeamNicknameActivity.REQ_CODE_TEAM_NAME && null != data)
		{
			//			Intent intent = getIntent();
			//			intent.putExtra(TeamNicknameActivity.EXTRA_NAME, data.getStringExtra(TeamNicknameActivity.EXTRA_NAME));
			setResult(RESULT_OK, data);
		}
	}
	
	/**
	 * ************************** 初始化 **************************
	 */
	
	protected void findViews() {
		listviewContainer = (ViewGroup) findViewById(R.id.message_activity_list_view_container);
		
		// input bar
		messageActivityBottomLayout = (LinearLayout) findViewById(R.id.messageActivityBottomLayout);
		messageInputBar = findViewById(R.id.textMessageLayout);
		switchToTextButtonInInputBar = findViewById(R.id.buttonTextMessage);
		switchToAudioButtonInInputBar = findViewById(R.id.buttonAudioMessage);
		moreFuntionButtonInInputBar = findViewById(R.id.buttonMoreFuntionInText);
		emojiButtonInInputBar = findViewById(R.id.emoji_button);
		sendMessageButtonInInputBar = findViewById(R.id.buttonSendMessage);
		messageEditText = (EditText) findViewById(R.id.editTextMessage);
		
		// 语音
		audioRecordBtn = (Button) findViewById(R.id.audioRecord);
		audioAnimLayout = (FrameLayout) findViewById(R.id.layoutPlayAudio);
		time = (Chronometer) findViewById(R.id.timer);
		timerTip = (TextView) findViewById(R.id.timer_tip);
		timerTipContainer = (LinearLayout) findViewById(R.id.timer_tip_container);
		
		// 表情
		emojiLayout = (LinearLayout) findViewById(R.id.message_activity_emoji_layout);
		viewPager = (ViewPager) findViewById(R.id.message_activity_emoji_viewpager);
		emojiPage = (LinearLayout) findViewById(R.id.message_activity_emoji_page);
		
		// 显示录音按钮
		switchToTextButtonInInputBar.setVisibility(View.GONE);
		switchToAudioButtonInInputBar.setVisibility(View.VISIBLE);
	}
	
	private void initInputBar() {
		switchToTextButtonInInputBar.setOnClickListener(clickListener);
		switchToAudioButtonInInputBar.setOnClickListener(clickListener);
		emojiButtonInInputBar.setOnClickListener(clickListener);
		sendMessageButtonInInputBar.setOnClickListener(clickListener);
		moreFuntionButtonInInputBar.setOnClickListener(clickListener);
		backBtn.setOnClickListener(clickListener);
	}
	
	/**
	 * *************** OnListViewEventListener ***************
	 */
	@Override
	public void onListViewStartScroll() {
		hideAllInputLaout();
	}
	
	@Override
	public void onListViewBlankDoubleClick() {
	}
	
	@Override
	public void onListViewSizeChanged(int w, int h, int oldw, int oldh) {
	}
	
	@Override
	public void onListViewScrollToBottom() {
	}
	
	private Runnable hideAllInputLayoutRunnable;
	
	private void hideAllInputLaout() {
		if (hideAllInputLayoutRunnable == null)
		{
			hideAllInputLayoutRunnable = new Runnable()
			{
				
				@Override
				public void run() {
					hideInputMethod();
					hideMoreFunctionLayout();
					hideEmojiLayout();
				}
			};
		}
		uiHandler.postDelayed(hideAllInputLayoutRunnable, ViewConfiguration.getDoubleTapTimeout());
	}
	
	/**
	 * *************** ViewHolderEventListener ***************
	 */
	@Override
	public boolean onViewHolderLongClick(View clickView, View viewHolderView, MsgListItem item) {
		if (needResponClickEvent())
		{
			showLongClickAction(item);
		}
		return true;
	}
	
	@Override
	public void onAudioStartPlay() {
	}
	
	@Override
	public void onAudioEndPlay() {
	}
	
	/**
	 * *************** IEmojiSelectedListener ***************
	 */
	
	@Override
	public void onEmojiSelected(String key) {
		Editable mEditable = messageEditText.getText();
		if (key.equals("/DEL"))
		{
			messageEditText.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
		}
		else
		{
			int start = messageEditText.getSelectionStart();
			int end = messageEditText.getSelectionEnd();
			start = (start < 0 ? 0 : start);
			end = (start < 0 ? 0 : end);
			mEditable.replace(start, end, key);
		}
	}
	
	/**
	 * ************************* 键盘布局切换 *******************************
	 */
	
	private OnClickListener clickListener = new View.OnClickListener()
	                                      {
		                                      
		                                      @Override
		                                      public void onClick(View v) {
			                                      if (v == switchToTextButtonInInputBar)
			                                      {
				                                      switchToTextLayout(true);// 显示文本发送的布局
			                                      }
			                                      else if (v == sendMessageButtonInInputBar)
			                                      {
				                                      onTextMessageSendButtonPressed();
			                                      }
			                                      else if (v == switchToAudioButtonInInputBar)
			                                      {
				                                      switchToAudioLayout();
			                                      }
			                                      else if (v == moreFuntionButtonInInputBar)
			                                      {
				                                      toggleMoreFunctionLayout();
			                                      }
			                                      else if (v == emojiButtonInInputBar)
			                                      {
				                                      toggleEmojiLayout();
			                                      }
			                                      else if (v == backBtn)
			                                      {
				                                      onBackPressed();
				                                      finish();
			                                      }
		                                      }
	                                      };
	
	// 点击edittext，切换键盘和更多布局
	private void switchToTextLayout(boolean needShowInput) {
		hideEmojiLayout();
		hideMoreFunctionLayout();
		
		audioRecordBtn.setVisibility(View.GONE);
		messageEditText.setVisibility(View.VISIBLE);
		switchToTextButtonInInputBar.setVisibility(View.GONE);
		switchToAudioButtonInInputBar.setVisibility(View.VISIBLE);
		
		messageInputBar.setVisibility(View.VISIBLE);
		
		if (needShowInput)
		{
			uiHandler.postDelayed(showTextRunnable, SHOW_LAYOUT_DELAY);
		}
		else
		{
			hideInputMethod();
		}
	}
	
	// 发送文本消息
	private void onTextMessageSendButtonPressed() {
		if (messageEditText.getText().toString().trim().length() > 140)
		{
			Util.showToast(context, "不能超过140字");
			return;
		}
		super.sendTextMessage(messageEditText.getText().toString());
		restoreText(true);
	}
	
	// 切换成音频，收起键盘，按钮切换成键盘
	private void switchToAudioLayout() {
		messageEditText.setVisibility(View.GONE);
		audioRecordBtn.setVisibility(View.VISIBLE);
		hideInputMethod();
		hideEmojiLayout();
		hideMoreFunctionLayout();
		
		switchToAudioButtonInInputBar.setVisibility(View.GONE);
		switchToTextButtonInInputBar.setVisibility(View.VISIBLE);
	}
	
	// 点击“+”号按钮，切换更多布局和键盘
	protected void toggleMoreFunctionLayout() {
		if (moreFuntionBottomLayout == null || moreFuntionBottomLayout.getVisibility() == View.GONE)
		{
			showMoreFunctionLayout();
		}
		else
		{
			hideMoreFunctionLayout();
		}
	}
	
	// 点击表情，切换到表情布局
	private void toggleEmojiLayout() {
		if (emojiLayout == null || emojiLayout.getVisibility() == View.GONE)
		{
			showEmojiLayout();
		}
		else
		{
			hideEmojiLayout();
		}
	}
	
	// 隐藏表情布局
	protected void hideEmojiLayout() {
		uiHandler.removeCallbacks(showEmojiRunnable);
		if (emojiLayout != null)
		{
			emojiLayout.setVisibility(View.GONE);
		}
	}
	
	// 隐藏更多布局
	private void hideMoreFunctionLayout() {
		uiHandler.removeCallbacks(showMoreFuncRunnable);
		if (moreFuntionBottomLayout != null)
		{
			moreFuntionBottomLayout.setVisibility(View.GONE);
		}
	}
	
	// 隐藏键盘布局
	private void hideInputMethod() {
		uiHandler.removeCallbacks(showTextRunnable);
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(messageEditText.getWindowToken(), 0);
		messageEditText.clearFocus();
	}
	
	// 隐藏语音布局
	private void hideAudioLayout() {
		audioRecordBtn.setVisibility(View.GONE);
		messageEditText.setVisibility(View.VISIBLE);
		switchToTextButtonInInputBar.setVisibility(View.VISIBLE);
		switchToAudioButtonInInputBar.setVisibility(View.GONE);
	}
	
	// 显示表情布局
	private void showEmojiLayout() {
		hideInputMethod();
		hideMoreFunctionLayout();
		hideAudioLayout();
		
		messageEditText.requestFocus();
		uiHandler.postDelayed(showEmojiRunnable, 200);
		emojiLayout.setVisibility(View.VISIBLE);
		if (gifView == null)
		{
			gifView = new EmoticonView(this, this, viewPager, emojiPage);
		}
		gifView.showEmojis();
	}
	
	// 初始化更多布局
	private void addMoreFunctionLayout() {
		if (moreFuntionBottomLayout == null)
		{
			View.inflate(this, R.layout.message_activity_more_function_layout, messageActivityBottomLayout);
			moreFuntionBottomLayout = findViewById(R.id.moreFuntionLayout);
			moreFuntionBottomLayoutHasSetup = false;
		}
		initMoreFunctionLayout();
	}
	
	// 显示键盘布局
	private void showInputMethod(EditText editTextMessage, boolean setSelection) {
		editTextMessage.requestFocus();
		if (setSelection)
		{
			editTextMessage.setSelection(editTextMessage.getText().length());
		}
		
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.showSoftInput(editTextMessage, 0);
		
		uiHandler.postDelayed(new Runnable()
		{
			@Override
			public void run() {
				ListViewUtil.scrollToBottom(messageListView);
			}
		}, 200);
	}
	
	// 显示更多布局
	private void showMoreFunctionLayout() {
		addMoreFunctionLayout();
		hideEmojiLayout();
		hideInputMethod();
		
		uiHandler.postDelayed(showMoreFuncRunnable, SHOW_LAYOUT_DELAY);
		uiHandler.postDelayed(new Runnable()
		{
			@Override
			public void run() {
				ListViewUtil.scrollToBottom(messageListView);
			}
		}, 250);
		
	}
	
	// 初始化具体more layout中的项目
	private void initMoreFunctionLayout() {
		if (moreFuntionBottomLayoutHasSetup) { return; }
		onMoreFunctionItemClickListener pictureFunctionItemClickListener = new onMoreFunctionItemClickListener()
		{
			
			@Override
			public void onItemClick() {
				pickImage(false, PICK_IMAGE_COUNT, PickImageActivity.FROM_LOCAL);
			}
		};
		
		onMoreFunctionItemClickListener takePictureFunctionItemClickListener = new onMoreFunctionItemClickListener()
		{
			
			@Override
			public void onItemClick() {
				pickImage(false, PICK_IMAGE_COUNT, PickImageActivity.FROM_CAMERA);
			}
		};
		
		onMoreFunctionItemClickListener videoFunctionItemClickListener = new onMoreFunctionItemClickListener()
		{
			
			@Override
			public void onItemClick() {
				hideInputMethod();
				if (videoMessageHelper == null)
				{
					initVideoMessageHelper();
				}
				videoMessageHelper.showVideoSource(rootView);
			}
		};
		
		//TODO fw location
		//        onMoreFunctionItemClickListener locationFunctionItemClickListener = new onMoreFunctionItemClickListener() {
		//
		//            @Override
		//            public void onItemClick() {
		//                openMyLocation();
		//            }
		//        };
		
		onMoreFunctionItemClickListener guessFunctionItemClickListener = new onMoreFunctionItemClickListener()
		{
			@Override
			public void onItemClick() {
				guess();
			}
		};
		onMoreFunctionItemClickListener audioChatFunctionItemClickListener = new onMoreFunctionItemClickListener()
		{
			@Override
			public void onItemClick() {
				String account;
				UserBean user = UserDao.getInstance(getApplicationContext()).getLastLoginUser();
				if (user == null)
				{
					account = NimCache.getAccount();
				}
				else
				{
					account = user.getImAccount();
				}
				NimAVChatActivity.launch(context, account, receiverid, AVChatType.AUDIO.getValue(), true);
			}
		};
		onMoreFunctionItemClickListener videoChatFunctionItemClickListener = new onMoreFunctionItemClickListener()
		{
			@Override
			public void onItemClick() {
				String account;
				UserBean user = UserDao.getInstance(getApplicationContext()).getLastLoginUser();
				if (user == null)
				{
					account = NimCache.getAccount();
				}
				else
				{
					account = user.getImAccount();
				}
				NimAVChatActivity.launch(context, account, receiverid, AVChatType.VIDEO.getValue(), true);
			}
		};

		onMoreFunctionItemClickListener fileFunctionItemClickListener = new onMoreFunctionItemClickListener()
		{
			@Override
			public void onItemClick() {
				chooseFile();
			}
		};
		
		moreFunctionItemHolders = new ArrayList<MoreFunctionItemHolder>();
		moreFunctionItemHolders.add(new MoreFunctionItemHolder(R.drawable.message_plus_photo_selector, R.string.input_panel_photo, pictureFunctionItemClickListener));
		moreFunctionItemHolders.add(new MoreFunctionItemHolder(R.drawable.message_plus_take_photo_selector, R.string.input_panel_take, takePictureFunctionItemClickListener));
		//TODO fw location and video
		//        moreFunctionItemHolders.add(new MoreFunctionItemHolder(R.drawable.message_plus_take_movie_selector,
		//                R.string.input_panel_video, videoFunctionItemClickListener));
		//        moreFunctionItemHolders.add(new MoreFunctionItemHolder(R.drawable.message_plus_location_selector,
		//                R.string.input_panel_location, locationFunctionItemClickListener));
		moreFunctionItemHolders.add(new MoreFunctionItemHolder(R.drawable.message_plus_caiquan_selector, R.string.input_panel_guess, guessFunctionItemClickListener));
		if (!isTeam())
		{
			moreFunctionItemHolders.add(new MoreFunctionItemHolder(R.drawable.message_plus_audio_chat_selector, R.string.input_panel_audio_call, audioChatFunctionItemClickListener));
			moreFunctionItemHolders.add(new MoreFunctionItemHolder(R.drawable.message_plus_video_chat_selector, R.string.input_panel_video_call, videoChatFunctionItemClickListener));
		}
		//TODO fw file
		//        moreFunctionItemHolders.add(new MoreFunctionItemHolder(R.drawable.message_plus_send_file_selector,
		//                R.string.input_panel_file, fileFunctionItemClickListener));
		customMoreFunction();
		
		initMoreFunctionAdapter();
		moreFuntionBottomLayoutHasSetup = true;
	}

	public abstract boolean isTeam();
	
	public void customMoreFunction() {
		
	}
	
	// 初始化更多布局adapter
	private void initMoreFunctionAdapter() {
		final int ITEM_COUNT_PER_GRID_VIEW = 8;
		final int gridViewCount = moreFunctionItemHolders.size() / ITEM_COUNT_PER_GRID_VIEW + (moreFunctionItemHolders.size() % ITEM_COUNT_PER_GRID_VIEW == 0 ? 0 : 1);
		final ViewPager moreFunctionViewPager = (ViewPager) findViewById(R.id.viewPager);
		moreFunctionViewPager.setAdapter(new MoreFunctionPagerAdapter(context, moreFunctionItemHolders, uiHandler, moreFunctionViewPager, gridViewCount));
		final ViewGroup indicator = initMoreFunctionPageListener(gridViewCount, moreFunctionViewPager);
		setIndicator(0, gridViewCount, indicator);
	}
	
	// 初始化更多布局PageListener
	private ViewGroup initMoreFunctionPageListener(final int gridViewCount, final ViewPager moreFunctionViewPager) {
		final ViewGroup indicator = (ViewGroup) findViewById(R.id.more_function_page_indicator);
		moreFunctionViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener()
		{
			
			@Override
			public void onPageSelected(int position) {
				setIndicator(position, gridViewCount, indicator);
			}
			
			@Override
			public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
				
			}
			
			@Override
			public void onPageScrollStateChanged(int state) {
				
			}
		});
		return indicator;
	}
	
	private void setIndicator(int current, int total, ViewGroup indicator) {
		if (total <= 1)
		{
			indicator.removeAllViews();
		}
		else
		{
			indicator.removeAllViews();
			for (int i = 0; i < total; i++)
			{
				ImageView imgCur = new ImageView(this);
				imgCur.setId(i);
				// 判断当前页码来更新
				if (i == current)
				{
					imgCur.setBackgroundResource(R.drawable.moon_page_selected);
				}
				else
				{
					imgCur.setBackgroundResource(R.drawable.moon_page_unselected);
				}
				
				indicator.addView(imgCur);
			}
		}
	}
	
	private Runnable showEmojiRunnable    = new Runnable()
	                                      {
		                                      @Override
		                                      public void run() {
			                                      emojiLayout.setVisibility(View.VISIBLE);
		                                      }
	                                      };
	
	private Runnable showMoreFuncRunnable = new Runnable()
	                                      {
		                                      @Override
		                                      public void run() {
			                                      moreFuntionBottomLayout.setVisibility(View.VISIBLE);
		                                      }
	                                      };
	
	private Runnable showTextRunnable     = new Runnable()
	                                      {
		                                      @Override
		                                      public void run() {
			                                      // textLayoutAlreadyShow表示TextLayout是否已经显, 如果已经显示,则继续操作时不需要把光标定位到最后
			                                      final boolean textLayoutAlreadyShow = (messageInputBar.getVisibility() == View.VISIBLE);
			                                      showInputMethod(messageEditText, !textLayoutAlreadyShow);
		                                      }
	                                      };
	
	/**
	 * ******************************** 文本 ***********************************
	 */
	
	private void initTextEdit() {
		messageEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
		messageEditText.setOnTouchListener(new OnTouchListener()
		{
			
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN)
				{
					switchToTextLayout(true);
				}
				return false;
			}
		});
		
		messageEditText.setOnFocusChangeListener(new OnFocusChangeListener()
		{
			
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				messageEditText.setHint("");
				checkSendButtonEnable(messageEditText);
			}
		});
		
		messageEditText.addTextChangedListener(new TextWatcher()
		{
			private int start;
			private int count;
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				this.start = start;
				this.count = count;
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				checkSendButtonEnable(messageEditText);
				MoonUtil.replaceEmoticons(context, s, start, count);
				int editEnd = messageEditText.getSelectionEnd();
				messageEditText.removeTextChangedListener(this);
				while (StringUtil.counterChars(s.toString()) > 5000 && editEnd > 0)
				{
					s.delete(editEnd - 1, editEnd);
					editEnd--;
				}
				messageEditText.setSelection(editEnd);
				messageEditText.addTextChangedListener(this);
				
				sendTypingCommand();
			}
			
		});
	}
	
	private void restoreText(boolean clearText) {
		if (clearText)
		{
			messageEditText.setText("");
		}
		
		checkSendButtonEnable(messageEditText);
	}
	
	protected void checkSendButtonEnable(EditText editText) {
		String textMessage = editText.getText().toString();
		if (!TextUtils.isEmpty(StringUtil.removeBlanks(textMessage)) && editText.hasFocus())
		{
			moreFuntionButtonInInputBar.setVisibility(View.GONE);
			sendMessageButtonInInputBar.setVisibility(View.VISIBLE);
		}
		else
		{
			sendMessageButtonInInputBar.setVisibility(View.GONE);
			moreFuntionButtonInInputBar.setVisibility(View.VISIBLE);
		}
	}
	
	/**
	 * ****************************** 语音 ***********************************
	 */
	private void initAudioRecordButton() {
		audioRecordBtn.setOnTouchListener(new OnTouchListener()
		{
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN)
				{
					touched = true;
					initAudioRecord();
					onStartAudioRecord();
				}
				else if (event.getAction() == MotionEvent.ACTION_CANCEL || event.getAction() == MotionEvent.ACTION_UP)
				{
					touched = false;
					onEndAudioRecord(isCancelled(v, event));
				}
				else if (event.getAction() == MotionEvent.ACTION_MOVE)
				{
					touched = false;
					cancelAudioRecord(isCancelled(v, event));
				}
				
				return false;
			}
		});
	}
	
	// 上滑取消录音判断
	private static boolean isCancelled(View view, MotionEvent event) {
		int[] location = new int[2];
		view.getLocationOnScreen(location);
		
		if (event.getRawX() < location[0] || event.getRawX() > location[0] + view.getWidth() || event.getRawY() < location[1] - 40) { return true; }
		
		return false;
	}
	
	private void initAudioRecord() {
		if (audioMessageHelper == null)
		{
			audioMessageHelper = new AudioRecorder(this, RecordType.AAC, AudioRecorder.DEFAULT_MAX_AUDIO_RECORD_TIME_SECOND, this);
		}
	}
	
	private void onStartAudioRecord() {
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		
		started = audioMessageHelper.startRecord();
		cancelled = false;
		if (started == false)
		{
			Toast.makeText(this, R.string.recording_init_failed, Toast.LENGTH_SHORT).show();
			return;
		}
		
		if (!touched) { return; }
		
		audioRecordBtn.setText(getResources().getString(R.string.record_audio_end));
		audioRecordBtn.setBackgroundResource(R.drawable.message_input_edittext_box_pressed);
		
		updateTimerTip(false); // 初始化语音动画状态
		playAudioRecordAnim();
	}
	
	private void onEndAudioRecord(boolean cancel) {
		getWindow().setFlags(0, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		
		audioMessageHelper.completeRecord(cancel);
		audioRecordBtn.setText(getResources().getString(R.string.record_audio));
		audioRecordBtn.setBackgroundResource(R.drawable.message_input_edittext_box);
		stopAudioRecordAnim();
	}
	
	private void cancelAudioRecord(boolean cancel) {
		// reject
		if (!started) { return; }
		// no change
		if (cancelled == cancel) { return; }
		
		cancelled = cancel;
		updateTimerTip(cancel);
	}
	
	private void updateTimerTip(boolean cancel) {
		if (cancel)
		{
			timerTip.setText(getResources().getString(R.string.recording_cancel_tip));
			timerTipContainer.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_red_half_angle));
		}
		else
		{
			timerTip.setText(getResources().getString(R.string.recording_cancel));
			timerTipContainer.setBackgroundResource(0);
		}
	}
	
	private void playAudioRecordAnim() {
		audioAnimLayout.setVisibility(View.VISIBLE);
		time.setBase(SystemClock.elapsedRealtime());
		time.start();
	}
	
	private void stopAudioRecordAnim() {
		audioAnimLayout.setVisibility(View.GONE);
		time.stop();
		time.setBase(SystemClock.elapsedRealtime());
	}
	
	// 录音状态回调
	@Override
	public void onRecordReady() {
		
	}
	
	@Override
	public void onRecordStart(File audioFile, RecordType recordType) {
		
	}
	
	@Override
	public void onRecordSuccess(File audioFile, long audioLength, RecordType recordType) {
		sendAudioMessage(receiverid, getSessionTypeEnum(), audioFile, audioLength);
	}
	
	@Override
	public void onRecordFail() {
		
	}
	
	@Override
	public void onRecordCancel() {
		
	}
	
	@Override
	public void onRecordReachedMaxTime(final int maxTime) {
		stopAudioRecordAnim();
		EasyAlertDialogHelper.createOkCancelDiolag(context, "", getString(R.string.recording_max_time), false, new OnDialogActionListener()
		{
			@Override
			public void doCancelAction() {
			}
			
			@Override
			public void doOkAction() {
				audioMessageHelper.handleEndRecord(true, maxTime);
			}
		}).show();
	}
	
	/**
	 * **************************** 图片选取 ***********************************
	 */
	private static class SendImageAfterResumeData
	{
		public static enum ImageSource {
			picker, preview,
		}
		
		public Intent      imageIntentData;
		public ImageSource imageSource;
		public boolean     local    = false;
		public boolean     snapchat = false;
		
		public void setNeedSendImage(Intent data, SendImageAfterResumeData.ImageSource imageSource, boolean local, boolean snapchat) {
			this.imageIntentData = data;
			this.imageSource = imageSource;
			this.local = local;
			this.snapchat = snapchat;
		}
	}
	
	private void pickImage(boolean b, int pickImageCount, int from) {
		hideInputMethod();
		pickImage(AbsMessageActivity.this, ActivityResultCode.PICK_IMAGE, rootView, true, pickImageCount, true, from);
	}
	
	private void pickImage(Activity activity, int requestCode, View rootView, boolean mutiSelect, int mutiSelectLimitSize, boolean isSupportOrig, int from) {
		if (activity == null) { return; }
		
		showSelector(rootView, activity, null, "", requestCode, mutiSelect, mutiSelectLimitSize, isSupportOrig, false, 0, 0, tempFile(), from);
	}
	
	private String tempFile() {
		String filename = StringUtil.get32UUID() + JPG;
		return StorageUtil.getWritePath(filename, StorageType.TYPE_TEMP);
	}
	
	private static void showSelector(View rootView, final Activity activity, final Fragment fragment, String title, final int requestCode, final boolean mutiSelect, final int mutiSelectLimitSize, final boolean isSupportOrig, final boolean crop, final int outputX, final int outputY, final String outPath, int from) {
		if (activity == null) { return; }
		if (from == PickImageActivity.FROM_LOCAL)
		{
			PickImageActivity.start(activity, requestCode, from, outPath, mutiSelect, mutiSelectLimitSize, isSupportOrig, crop, outputX, outputY);
		}
		else if (from == PickImageActivity.FROM_CAMERA)
		{
			PickImageActivity.start(activity, requestCode, from, outPath, mutiSelect, 1, isSupportOrig, crop, outputX, outputY);
		}
		
	}
	
	// 图片选取回调
	private void onPickImageActivityResult(Intent data, int requestCode) {
		if (data == null)
		{
			Toast.makeText(this, R.string.picker_image_error, Toast.LENGTH_LONG).show();
			return;
		}
		
		boolean local = data.getBooleanExtra(Extras.EXTRA_FROM_LOCAL, false);
		// 本地相册
		if (local)
		{
			setNeedSendImage(data, SendImageAfterResumeData.ImageSource.picker, true, false);
		}
		// 拍照
		else
		{
			Intent intent = new Intent();
			if (!handleImagePath(intent, data)) { return; }
			intent.setClass(this, PreviewImageFromCameraActivity.class);
			startActivityForResult(intent, ActivityResultCode.PREVIEW_IMAGE_FROM_CAMERA);
		}
	}
	
	private boolean handleImagePath(Intent intent, Intent data) {
		String photoPath = data.getStringExtra(Extras.EXTRA_FILE_PATH);
		if (TextUtils.isEmpty(photoPath))
		{
			Toast.makeText(this, R.string.picker_image_error, Toast.LENGTH_LONG).show();
			return false;
		}
		
		File imageFile = new File(photoPath);
		intent.putExtra("OrigImageFilePath", photoPath);
		File scaledImageFile = ImageUtil.getScaledImageFileWithMD5(imageFile, MIME_JPEG);
		
		boolean local = data.getExtras().getBoolean(Extras.EXTRA_FROM_LOCAL, true);
		if (!local)
		{
			// 删除拍照生成的临时文件
			AttachmentStore.delete(photoPath);
		}
		
		if (scaledImageFile == null)
		{
			Toast.makeText(this, R.string.picker_image_error, Toast.LENGTH_LONG).show();
			return false;
		}
		else
		{
			ImageUtil.makeThumbnail(this, scaledImageFile);
		}
		intent.putExtra("ImageFilePath", scaledImageFile.getAbsolutePath());
		return true;
	}
	
	public void setNeedSendImage(Intent data, SendImageAfterResumeData.ImageSource imageSource, boolean local, boolean snapchat) {
		if (sendImageAfterResumeData == null)
		{
			sendImageAfterResumeData = new SendImageAfterResumeData();
		}
		
		sendImageAfterResumeData.setNeedSendImage(data, imageSource, local, snapchat);
	}
	
	private void sendImageAfterResume() {
		if (sendImageAfterResumeData != null)
		{
			if (sendImageAfterResumeData.imageSource == SendImageAfterResumeData.ImageSource.preview)
			{
				sendImageAfterPreviewPhotoActivityResult(sendImageAfterResumeData.imageIntentData, sendImageAfterResumeData.snapchat);
			}
			else if (sendImageAfterResumeData.imageSource == SendImageAfterResumeData.ImageSource.picker)
			{
				sendImageAfterSelfImagePicker(sendImageAfterResumeData.imageIntentData);
			}
			sendImageAfterResumeData = null;
		}
	}
	
	private void sendImageAfterPreviewPhotoActivityResult(Intent data, final boolean snapchat) {
		SendImageHelper.sendImageAfterPreviewPhotoActivityResult(uiHandler, data, new SendImageHelper.Callback()
		{
			
			@Override
			public void sendImage(File file, boolean isOrig) {
				sendImageMessage(receiverid, getSessionTypeEnum(), file, isOrig);
			}
		});
	}
	
	private void sendImageAfterSelfImagePicker(final Intent data) {
		SendImageHelper.sendImageAfterSelfImagePicker(this, data, new SendImageHelper.Callback()
		{
			
			@Override
			public void sendImage(File file, boolean isOrig) {
				sendImageMessage(receiverid, getSessionTypeEnum(), file, isOrig);
			}
		});
	}
	
	// 拍摄回调
	private void onPreviewImageActivityResult(int requestCode, int resultCode, Intent data) {
		boolean local = false;
		boolean snapchat = false;
		
		if (requestCode == ActivityResultCode.PREVIEW_IMAGE_FROM_CAMERA)
		{
			local = false;
			snapchat = false;
		}
		if (data.getBooleanExtra(PreviewImageFromCameraActivity.RESULT_SEND, false))
		{
			setNeedSendImage(data, SendImageAfterResumeData.ImageSource.preview, local, snapchat);
		}
		else if (data.getBooleanExtra(PreviewImageFromCameraActivity.RESULT_RETAKE, false))
		{
			String filename = StringUtil.get32UUID() + JPG;
			String path = StorageUtil.getWritePath(filename, StorageType.TYPE_TEMP);
			
			if (requestCode == ActivityResultCode.PREVIEW_IMAGE_FROM_CAMERA)
			{
				PickImageActivity.start(this, ActivityResultCode.PICK_IMAGE, PickImageActivity.FROM_CAMERA, path);
			}
		}
	}
	
	/**
	 * ********************************* 位置 ************************************
	 */
	//TODO fw 地址信息
	//    private void openMyLocation() {
	//        if (!NimLocationManager.isLocationEnable(this)) {
	//            final EasyAlertDialog alertDialog = new EasyAlertDialog(this);
	//            alertDialog.setMessage("位置服务未开启");
	//            alertDialog.addNegativeButton("取消", EasyAlertDialog.NO_TEXT_COLOR, EasyAlertDialog.NO_TEXT_SIZE,
	//                    new OnClickListener() {
	//
	//                        @Override
	//                        public void onClick(View v) {
	//                            alertDialog.dismiss();
	//                        }
	//                    });
	//            alertDialog.addPositiveButton("设置", EasyAlertDialog.NO_TEXT_COLOR, EasyAlertDialog.NO_TEXT_SIZE,
	//                    new OnClickListener() {
	//
	//                        @Override
	//                        public void onClick(View v) {
	//                            alertDialog.dismiss();
	//                            Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
	//                            try {
	//                                context.startActivity(intent);
	//                            } catch (Exception e) {
	//                                LogUtil.e(TAG, "start ACTION_LOCATION_SOURCE_SETTINGS error");
	//                            }
	//
	//                        }
	//                    });
	//            alertDialog.show();
	//            return;
	//        }
	//
	//        LocationHelper.toLocationForResult(this, ActivityResultCode.LOCATION_ACTIVITY_CODE);
	//    }
	
	private void guess() {
		GuessAttachment attachment = new GuessAttachment();
		IMMessage message = MessageBuilder.createCustomMessage(receiverid, getSessionTypeEnum(), attachment);
		sendMessage(message);
	}
	
	/**
	 * ******************************* 消息提醒
	 * **************************************
	 */
	// 初始化底部新信息提示条
	private void initNewMessageTip() {
		View.inflate(this, R.layout.new_message_tip_layout, listviewContainer);
		newMessageTipLayout = listviewContainer.findViewById(R.id.new_message_tip_layout);
		newMessageTipLayout.setOnClickListener(new OnClickListener()
		{
			
			@Override
			public void onClick(View v) {
				setSelectionAfterFirstLoad();
				newMessageTipLayout.setVisibility(View.GONE);
			}
		});
		newMessageTipTextView = (TextView) newMessageTipLayout.findViewById(R.id.new_message_tip_text_view);
		newMessageTipHeadImageView = (HeadImageView) newMessageTipLayout.findViewById(R.id.new_message_tip_head_image_view);
	}
	
	@Override
	protected void showIncomingMessageTip(IMMessage newMessage, boolean needScrollToBottom) {
		if (!needScrollToBottom)
		{
			// 显示底部新信息提示条
			if (newMessageTipLayout == null)
			{
				initNewMessageTip();
			}
			
			if (!TextUtils.isEmpty(newMessage.getFromAccount()))
			{
				newMessageTipHeadImageView.loadBuddyHeadImage(newMessage.getFromAccount());
			}
			else
			{
				newMessageTipHeadImageView.resetImageView();
				newMessageTipHeadImageView.setImageResource(R.drawable.avatar_def);
			}
			
			MoonUtil.identifyFaceExpression(this, newMessageTipTextView, MessageHelper.getMsgShowText(newMessage), ImageSpan.ALIGN_BOTTOM);
			newMessageTipLayout.setVisibility(View.VISIBLE);
			uiHandler.removeCallbacks(showNewMessageTipLayoutRunnable);
			uiHandler.postDelayed(showNewMessageTipLayoutRunnable, 5 * 1000);
		}
		else
		{
			ListViewUtil.scrollToBottom(messageListView);
		}
	}
	
	private Runnable showNewMessageTipLayoutRunnable = new Runnable()
	                                                 {
		                                                 
		                                                 @Override
		                                                 public void run() {
			                                                 newMessageTipLayout.setVisibility(View.GONE);
		                                                 }
	                                                 };
	
	private void setSelectionAfterFirstLoad() {
		ListViewUtil.scrollToBottom(messageListView);
	}
	
	private void removeHandlerCallback() {
		if (showNewMessageTipLayoutRunnable != null)
		{
			uiHandler.removeCallbacks(showNewMessageTipLayoutRunnable);
		}
	}
	
	// 正在输入
	protected void sendTypingCommand() {
	}
	
	/**
	 * ****************************** 长按菜单 ********************************
	 */
	
	// 判断是否响应item长按事件
	private boolean needResponClickEvent() {
		if (audioMessageHelper != null && audioMessageHelper.isRecording())
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	
	// 长按消息Item后弹出菜单控制
	private void showLongClickAction(MsgListItem selectedItem) {
		IMMessage selectedMessageHistory = selectedItem.getMessage();
		
		CustomAlertDialog alertDialog = new CustomAlertDialog(this);
		alertDialog.setCancelable(true);
		alertDialog.setCanceledOnTouchOutside(true);
		
		prepareDialogItems(selectedItem, selectedMessageHistory, alertDialog);
		alertDialog.show();
	}
	
	// 长按消息item的菜单项准备
	private void prepareDialogItems(final MsgListItem selectedItem, final IMMessage selectedMessageHistory, CustomAlertDialog alertDialog) {
		MsgTypeEnum msgType = selectedMessageHistory.getMsgType();
		
		// 0 resend
		longClickItemResend(selectedItem, selectedMessageHistory, alertDialog);
		// 1 copy
		longClickItemCopy(selectedItem, alertDialog, msgType);
		// 2 delete
		longClickItemDelete(selectedItem, alertDialog);
		//3 forward
		longClickItemForward(selectedItem, alertDialog, msgType);
	}
	
	// 长按菜单项--重发
	private void longClickItemResend(final MsgListItem selectedItem, final IMMessage selectedMessageHistory, CustomAlertDialog alertDialog) {
		boolean showResend = false;
		if (selectedMessageHistory.getStatus() == MsgStatusEnum.fail)
		{
			showResend = true;
		}
		if (showResend)
		{
			alertDialog.addItem(getString(R.string.repeat_send_has_blank), new onSeparateItemClickListener()
			{
				
				@Override
				public void onClick() {
					onResendMessageItem(selectedItem.getMessage());
				}
			});
		}
	}
	
	private void onResendMessageItem(IMMessage message) {
		int index = getItemIndex(message.getUuid());
		if (index >= 0)
		{
			showResendConfirm(message, index); // 重发确认
		}
	}
	
	private void showResendConfirm(final IMMessage message, final int index) {
		OnDialogActionListener listener = new OnDialogActionListener()
		{
			
			@Override
			public void doCancelAction() {
			}
			
			@Override
			public void doOkAction() {
				resendMessage(message);
			}
		};
		final EasyAlertDialog dialog = EasyAlertDialogHelper.createOkCancelDiolag(this, null, getString(R.string.repeat_send_message), true, listener);
		dialog.show();
	}
	
	// 长按菜单项--复制
	private void longClickItemCopy(final MsgListItem selectedItem, CustomAlertDialog alertDialog, MsgTypeEnum msgType) {
		boolean showCopy = false;
		if (msgType == MsgTypeEnum.text)
		{
			showCopy = true;
		}
		if (showCopy)
		{
			alertDialog.addItem(getString(R.string.copy_has_blank), new onSeparateItemClickListener()
			{
				
				@Override
				public void onClick() {
					onCopyMessageItem(selectedItem);
				}
			});
		}
	}
	
	protected void onCopyMessageItem(MsgListItem messageItem) {
		IMMessage message = messageItem.getMessage();
		ClipboardUtil.clipboardCopyText(this, message.getContent());
	}
	
	// 长按菜单项--删除
	private void longClickItemDelete(final MsgListItem selectedItem, CustomAlertDialog alertDialog) {
		alertDialog.addItem(getString(R.string.delete_has_blank), new onSeparateItemClickListener()
		{
			
			@Override
			public void onClick() {
				onDeleteMessageItem(selectedItem);
			}
		});
	}
	
	private void onDeleteMessageItem(MsgListItem messageItem) {
		if (messageItem.getMessage() == null) { return; }
		
		int index = getItemIndex(messageItem.getMessage().getUuid());
		if (index < 0) { return; }
		
		items.remove(index);
		NIMClient.getService(MsgService.class).deleteChattingHistory(messageItem.getMessage());
		relocateShowTimeItemAfterDelete(messageItem, index);
		refreshMessageList();
	}
	
	// 删除消息后重置时间显示
	private void relocateShowTimeItemAfterDelete(MsgListItem messageItem, int index) {
		// 如果被删的项显示了时间，需要继承
		if (messageItem.needShowTime)
		{
			if (items.size() > 0)
			{
				MsgListItem nextItem;
				if (index == items.size())
				{
					//删除的是最后一项
					nextItem = items.get(index - 1);
				}
				else
				{
					//删除的不是最后一项
					nextItem = items.get(index);
				}
				
				// 增加其他不需要显示时间的消息类型判断
				if (nextItem.hideTimeAlways())
				{
					nextItem.needShowTime = false;
					if (lastShowTimeItem != null && lastShowTimeItem.getMessage() != null && lastShowTimeItem.getMessage().isTheSame(messageItem.getMessage()))
					{
						lastShowTimeItem = null;
						for (int i = items.size() - 1; i >= 0; i--)
						{
							MsgListItem item = items.get(i);
							if (item.needShowTime == true)
							{
								lastShowTimeItem = item;
								break;
							}
						}
					}
				}
				else
				{
					nextItem.needShowTime = true;
					
					if (lastShowTimeItem == null || (lastShowTimeItem.getMessage() != null && lastShowTimeItem.getMessage().isTheSame(messageItem.getMessage())))
					{
						lastShowTimeItem = nextItem;
					}
				}
			}
			else
			{
				lastShowTimeItem = null;
			}
		}
	}
	
	// 长按菜单项--转发
	private void longClickItemForward(final MsgListItem selectedItem, CustomAlertDialog alertDialog, final MsgTypeEnum msgType) {
		boolean showForward = false;
		if (msgType == MsgTypeEnum.image)
		{
			showForward = true;
		}
		if (showForward)
		{
			alertDialog.addItem(getString(R.string.forward_has_blank), new onSeparateItemClickListener()
			{
				
				@Override
				public void onClick() {
					//转发
					onForwardItemMessage(selectedItem);
					//				Toast.makeText(context, "我要转发了~~", 1000).show();
				}
			});
		}
	}
	
	private void onForwardItemMessage(MsgListItem selectedItem) {
		Intent intent = new Intent(AbsMessageActivity.this, NewInteractionCreateTeamChMActivity.class);
		intent.putExtra(DefaultConsts.NI_CONTACT_INTENT, DefaultConsts.NI_CONTACT_FORWARD);
		intent.putExtra("message", selectedItem);
		startActivity(intent);
		//		finish();
	}
	
	/**
	 * ************************* 菜单 *******************************
	 */
	protected int getMenuRes() {
		return 0;
	}
	
	protected void onMenuKeyPressed(int id) {
	}
	
	/**
	 * ********************** 视频 *******************************
	 */
	private void initVideoMessageHelper() {
		videoMessageHelper = new VideoMessageHelper(this, new VideoMessageHelperListener()
		{
			
			@Override
			public void onVideoPicked(File file, long duration, int width, int height, String md5) {
				// send video
				sendVideoMessage(receiverid, getSessionTypeEnum(), file, duration, width, height, md5);
			}
		});
	}
	
	/**
	 * **********************文件************************
	 */
	private void chooseFile() {
		FileBrowserActivity.startActivityForResult(this, ActivityResultCode.GET_LOCAL_FILE);
	}
	
	private void sendLocalFile(String path) {
		File file = new File(path);
		sendFileMessage(receiverid, getSessionTypeEnum(), file);
	}
	
}
